// src/index.ts
import { join } from "path";
import { paramCase } from "param-case";

// src/utils.ts
import Module from "module";
import { sep, resolve } from "path";
import { existsSync } from "fs";
import { parseSync } from "@swc/core";
var createRequire = Module.createRequire || Module.createRequireFromPath;
var parseImportModule = function(code, libList) {
  const ast = parseSync(code, {
    syntax: "typescript",
    tsx: true
  }).body;
  const importMaps = {};
  ast.forEach((astNode) => {
    if (astNode.type !== "ImportDeclaration") return;
    const libraryName = astNode.source.value;
    const matchLib = libList.find((lib) => lib.libraryName === libraryName);
    if (!matchLib) return;
    if (astNode.specifiers.length === 0) return;
    astNode.specifiers.forEach((item) => {
      if (item.type === "ImportNamespaceSpecifier") {
        console.warn(`Can't transform code`);
        return;
      }
      let name;
      if (item.type === "ImportDefaultSpecifier") {
        name = "default";
      } else if (item.local.type === "Identifier") {
        name = item.local.value;
      } else if (item.local.name) {
        name = item.local.name;
      }
      if (importMaps[libraryName]) {
        importMaps[libraryName].push(name);
      } else {
        importMaps[libraryName] = [name];
      }
    });
  });
  return { importMaps };
};
var codeIncludesLibraryName = (code, libList = []) => {
  return !libList.every(({ libraryName }) => {
    return !new RegExp(`('${libraryName}')|("${libraryName}")`).test(code);
  });
};
var stylePathHandler = (stylePath, ignoreStylePathNotFound = true) => {
  let str = "";
  if (isString(stylePath) && stylePath) {
    str += stylePathNotFoundHandler(stylePath, ignoreStylePathNotFound);
  } else if (Array.isArray(stylePath)) {
    stylePath.forEach((item) => {
      str += stylePathNotFoundHandler(item, ignoreStylePathNotFound);
    });
  }
  return str;
};
var stylePathNotFoundHandler = (stylePath, ignoreStylePathNotFound) => {
  if (ignoreStylePathNotFound) {
    let stylePathExists = true;
    try {
      createRequire(process.cwd() + sep).resolve(stylePath);
    } catch (error) {
      stylePathExists = error?.code !== "MODULE_NOT_FOUND";
    }
    if (!stylePathExists) {
      const fullStylePath = resolve(process.cwd(), "node_modules", stylePath);
      const lastPath = fullStylePath.split("/").pop();
      if (!lastPath?.includes(".")) {
        const possibleEndWithsPaths = [
          "/index.js",
          "/index.mjs",
          ".js",
          ".mjs"
        ];
        if (possibleEndWithsPaths.some((p) => existsSync(fullStylePath + p))) {
          stylePathExists = true;
        }
      }
    }
    if (stylePathExists) {
      return `import '${stylePath}';`;
    } else {
      console.warn(`${stylePath} is not found!`);
      return "";
    }
  }
  return `import '${stylePath}';`;
};
var isString = (obj) => typeof obj === "string";
var isFunction = (x) => Object.prototype.toString.call(x) == "[object Function]";
var isBool = (obj) => typeof obj === "boolean";

// src/index.ts
var swcImportLoader = function(content) {
  const options = this.getOptions();
  if (options.rspackExperiments && options.rspackExperiments.import) {
    const libList = options.rspackExperiments.import || [];
    const ignoreStylePathNotFound = options.rspackExperiments.ignoreStylePathNotFound || true;
    const hasCodeIncludesLibraryName = codeIncludesLibraryName(content, libList);
    if (hasCodeIncludesLibraryName) {
      const { importMaps } = parseImportModule(content, libList);
      let importStr = "";
      libList.forEach(({ libraryName, libraryDirectory, style, camel2DashComponentName = true }) => {
        if (importMaps[libraryName]) {
          importMaps[libraryName].forEach((item) => {
            if (camel2DashComponentName) {
              item = paramCase(item);
            }
            let stylePath;
            let prefixPath = libraryName;
            if (libraryDirectory) {
              prefixPath = join(libraryName, libraryDirectory);
            }
            if (isFunction(style)) {
              stylePath = style(join(prefixPath, item), item);
            } else if (isBool(style)) {
              stylePath = join(prefixPath, item, "style");
            } else if (style == "css") {
              stylePath = join(prefixPath, item, "style", "css");
            } else {
              stylePath = join(prefixPath, item);
            }
            const styleImportString = stylePathHandler(stylePath, ignoreStylePathNotFound);
            if (styleImportString) {
              importStr += styleImportString + "\n";
            }
          });
        }
      });
      return importStr + content;
    }
  }
  return content;
};
var index_default = swcImportLoader;
export {
  index_default as default
};
